﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HammerMUD.System;

namespace HammerMUD.Accounts
{
    public class LogInUtilities
    {
        public static void ProcessLogin(String line, User user, List<Account> accounts)
        {
            switch (user.CurrentState.LogIn)
            {
                case LogInState.NotLoggedIn:
                    LogIn(line, user, accounts, HammerMUD.System.HammerMUD.Users);
                    break;
                case LogInState.WaitingOnPassword:
                    Password(line, user);
                    break;
                default:
                    Console.WriteLine("Error! Invalid log in state!");
                    break;
            }
        }

        public static void LogIn(String line, User user, List<Account> accounts, List<User> users)
        {
            // Kick existing connections
            foreach (User u in users)
            {
                if (u.UserAccount != null && u.UserAccount.Name.ToLower().Equals(line.ToLower()))
                {
                    u.Close();
                }
            }

            // Search for accounts
            foreach (Account a in accounts)
            {
                if (line.ToLower().Equals(a.Name.ToLower()))
                {
                    user.UserAccount = a;
                    user.CurrentState.LogIn = LogInState.WaitingOnPassword;
                    user.Prompt("Password: ");
                    return;
                }
            }

            user.Send("Account " + line + " not found!");
            user.Prompt("Would you like to create a new account? ");
            user.UserAccount = new Account() { Name = line.Trim(), Password = "" };
            user.CurrentState.Base = BaseState.NewAccount;
            user.CurrentState.NewAccount = NewAccountState.Confirmation;
        }

        public static void Password(string line, User user)
        {
            if (line.Equals(user.UserAccount.Password))
            {
                user.UserAccount.User = user;
                user.Send(AccountMenuUtilities.AccountMenu);
                user.CurrentState.Base = BaseState.AccountMenu;
                user.CurrentState.AccountMenu = AccountMenuState.Menu;
                user.Send("Logged in as " + user.UserAccount.Name);
            }
            else
            {
                //AdminUtilities.SecurityLog("Password failure for account " + user.UserAccount.Name);
                user.Send("Password is incorrect! The failure has been logged.");
                user.Prompt("Re-enter your password: ");
            }
        }
    }
}
